<template>
  <div class="task-list-wrap">

    <div class="header-top">
      <div class="add-task-btn" v-if="btnAuth.createTaskAuth">
        <el-button class="mb_12" type="primary" size="mini" @click="addOrEditTask('add')">{{ this.$t('projectManage.setting.taskSetting.createTask') }}</el-button>
      </div>
      <div class="pop-item">
        <el-popover
          placement="top-start"
          width="200"
          trigger="manual"
          :content="$t('common.projectManage.popTip1')"
          v-model="popVisible">
        </el-popover>
      </div>
    </div>
 

    <template v-if="dataList.length">
      <el-table
        v-table-style
        v-loading="listLoading"
        :data="dataList"
        header-row-class-name="common-list-table-header__v2"
        border
      >
        <el-table-column
          v-for="(column, index) in columns"
          :key="`${column.field}_${index}`"
          :label="column.displayName"
          :prop="column.field"
          :min-width="column.minWidth || '108px'"
          show-overflow-tooltip
        >
        <template slot-scope="scope">
          <template v-if="column.field === 'taskNumber'">
            <div class="view-detail-btn" @click="openTaskViewTab(scope.row)">{{ scope.row.taskNumber }}</div>
          </template>
          <template v-if="column.field === 'projectTaskName'">
            <div class="align-items-center">
              <div class="view-detail-btn">{{ scope.row.projectTaskName }} 
                <el-tag class="mar-r-5 mar-b-12" effect="plain" v-if="scope.row.isPreTask"> {{ $t('projectManage.setting.taskSetting.presetTag') }}</el-tag>
              </div>
              <ProjectTaskLabel class="ml_8" :current-row-data="scope.row"/>
            </div>
          </template>
          <template v-else-if="column.field === 'taskType'">
            <span>{{ taskTypeMap[scope.row.taskType] }}/{{ scope.row.taskFormName}}</span>
          </template>

          <template v-else-if="column.field === 'taskProgress'" >
            <el-progress :percentage="scope.row.taskProgress" class="table-blacklist"></el-progress>
          </template>

          <template v-else-if="column.field === 'taskStatus'" >
            <span class="status-tag" :style="stateBGC(scope.row.taskStatus)">
              {{ formatStatus(scope.row.taskStatus) }}
            </span>
          </template>
          
          <template v-else-if="column.field === 'planStartTime'" >
            {{scope.row.planStartTime | fmt_date}}
          </template>

          <template v-else-if="column.field === 'planEndTime'" >
            {{scope.row.planEndTime | fmt_date}}
          </template>

          <template v-else-if="column.field === 'preTaskInfoList'" >
            {{preTaskIdStr(scope.row.preTaskInfoList)}}
          </template>

          <template v-else-if="column.field === 'manager'" >
            {{scope.row.manager && scope.row.manager.map(i=>i.displayName).join('，') }}
          </template>

          <template v-else>
            {{ scope.row[column.field] }}
          </template>
        </template>
        </el-table-column>
        <el-table-column fixed="right" :label="$t('common.base.operation')" width="220">
          <!-- 要根据权限展示 -->
          <template slot-scope="scope">
            <!-- 草稿状态只显示提交和删除按钮 -->
            <template v-if="scope.row.taskStatus === 'DRAFT'">
              <!-- 草稿状态的任务“提交”按钮由“新建任务”权限控制是否显示 -->
              <el-button v-if="btnAuth.createTaskAuth" type="text" size="small" @click="addOrEditTask('draft', scope.row)">{{$t('common.base.submit')}}</el-button>
            </template>
            <template v-else>
              <el-button type="text" size="small" @click="openTaskViewTab(scope.row)">{{$t('common.base.view')}}</el-button>
              <el-button v-if="isCanEdit(scope.row)" type="text" size="small" @click="addOrEditTask('edit',scope.row)">{{$t('common.base.edit')}}</el-button>
              <el-button v-if="isCanEdit(scope.row)" type="text"  @click="updateProgress(scope.row)">{{$t('projectManage.taskManageView.updateProgress')}}</el-button>
            </template>
            <el-button class="text-danger" v-if="isCanDelete(scope.row)" type="text" size="small" @click="taskDelete(scope.row)">{{$t('common.base.delete')}}</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagping-box">
        <el-pagination
          class="base-pagination"
          :background="true"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="pageInfo.pageNo"
          :page-sizes="defaultTableData.defaultPageSizes"
          :page-size="pageInfo.pageSize"
          :layout="defaultTableData.defaultLayout"
          :total="total">
        </el-pagination>
      </div>
    </template>
    <template v-else>
      <no-data-view-new
        v-show="!listLoading"
        :notice-msg="$t('projectManage.taskManageView.actionText1')"
        :canClick="true"
        :actionText="$t('projectManage.setting.taskSetting.createTask')"
        @goAction="addOrEditTask('add')"
      ></no-data-view-new>
    </template>
    <!-- 创建任务弹窗 -->
    <create-project-task 
    ref="CreateProjectTaskModal" 
    :project-id="projectId" 
    :template-id="templateId"
    :projectPlanTime="projectPlanTime"
    @submitTask="submitTask" 
    @jumpPersonTab="jumpPersonTab"
    @updateList="getTableData"></create-project-task>
    <!-- 更新进度弹窗 -->
    <update-progress-dialog 
    ref="UpdateProgressDialog" 
    :taskProgress="detailData.taskProgress" 
    @submit="handelProgressSubmit"></update-progress-dialog>
  </div>
</template>

<script>

import * as ProjectManage from '@src/api/ProjectManage.ts';
import CreateProjectTask from '@src/modules/setting/projectManage/components/TaskSettings/components/CreateProjectTask.vue'
import { toast } from '@src/util/platform';
import { PageRoutesTypeEnum } from 'pub-bbx-global/pageType/dist/enum/PageRoutesEnum';
import _ from 'lodash';

import { taskTypeMap } from '@src/modules/projectManage/productTypeUtils/fixFields.js';

import { formatStatus, stateBGC } from '@src/modules/projectManage/taskManageList/util/index';
import { openAccurateTab } from '@src/util/platform';
import NoDataViewNew from '@src/component/common/NoDataViewNew';
import UpdateProgressDialog from '@src/modules/projectManage/taskManageView/components/UpdateProgressDialog.vue';
import { defaultTableData } from '@src/util/table'
import ProjectTaskLabel from '@src/modules/projectManage/components/projectTaskLabel.vue'
import { useOpenTab } from '@src/modules/projectManage/taskManageList/hooks/useOpenTab';
const { openTaskManageViewTab } = useOpenTab();

export default {
  name: 'project-type-task-list',
  data() {
    return {
      taskTypeMap,
      defaultTableData,
      columns: this.fixedColumns(),
      listLoading: false,
      dataList: [],
      total: 0,
      pageInfo:{
        pageNo: 1,
        pageSize: 10, 
      },
      // typeOptions: [],
      taskForm: {}, // 任务表单

      // 进度弹窗
      detailData: {
        taskProgress: 0,
        // id: ''
      },
      commonTaskForm: {}, // 任务配置表单
      taskDetailForm: {}, // 任务表单的集合
      formatStatus,
      stateBGC,
    }
  },
  props: {
    templateId: {
      type: String | Number,
      default: '',
    },
    projectId: {
      type: String | Number,
      default: '',
    },
    // 权限
    btnAuth: {
      type: Object,
      default: () => ({}),
    },
    projectPlanTime: {
      type: Object,
      default: () => ({}),
    }
  },
  components: {
    CreateProjectTask,
    NoDataViewNew,
    UpdateProgressDialog,
    ProjectTaskLabel
  },
  mounted() {
    this.getTableData()
  },
  computed: {
    popVisible: {
      // 只要有一个是草稿状态就展示
      get(){
        return this.dataList.some((item) => item.taskStatus === 'DRAFT')
      },
      set(v) {
        return v;
      }
    }
  },
  methods: {
    jumpPersonTab() {
      this.$refs.CreateProjectTaskModal.closeDialog()
      this.$emit('jumpPersonTab');
    },
    preTaskIdStr(value) {
      if (!value || !Array.isArray(value) || !value.length) return '';
      return value.map(item => item.name).join('，');
    },
    formatName(type) {
      if (!type) return '';
      let res;
      switch (type) {
      case 'COMMON_TASK':
        res = this.$t('common.projectManage.commonTask'); 
        break;
      default:
        break;
      } 
      return res; 
    },
    getTableData() {
      this.listLoading = true
      let params = {
        projectId: this.projectId,
        pageNo: this.pageInfo.pageNo,
        pageSize: this.pageInfo.pageSize,
        queryScene: 'PROJECT_DETAIL',
      }
      ProjectManage.projectTaskDetail(params).then((res) => {
        this.listLoading = false
        if (!res.success) return this.$message.error(res.message)
        this.dataList = res.data.list || []
        this.total = res.data.total || 0
      })
    },

    // 是否可以删除
    isCanDelete(row) {
      return row.hasDeleteAuth && row.taskStatus !== 'CANCEL'
    },

    // <!-- 编辑权限/ 未开始和进行中  未取消才可以编辑 -->
    isCanEdit(row) {
      return row.hasEditAuth && (row.taskStatus  === 'NO_START' || row.taskStatus === 'IN_PROGRESS') && row.taskStatus !== 'CANCEL'
    },
    // 切换页数
    handleCurrentChange(val) {
      this.pageInfo.pageNo = val;
      this.getTableData()
    },

    handleSizeChange(val) {
      this.pageInfo.pageNo = 1
      this.pageInfo.pageSize = val
      this.getTableData()
    },

    // 编辑任务
    async addOrEditTask(type, item) {
      if (type === 'add') {
        this.$refs.CreateProjectTaskModal.openDialog({}, false, type)
      } else {
        await this.getTaskDetail(item, type)
      }
    },
    // 更新进度弹窗
    updateProgress(row) {
      this.detailData = {}
      this.detailData.taskProgress = row.taskProgress
      this.detailData.id = row.id
      this.detailData.projectId = row.projectId

      setTimeout(() => {
        this.$refs.UpdateProgressDialog.openDialog()
      }, 100)
    },

    async handelProgressSubmit(form) {
      const params = {
        ...form,
        id: this.detailData.id,
        projectId: this.detailData.projectId
      }
      await ProjectManage.updateTaskManageProgress(params).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        this.$refs.UpdateProgressDialog.handleClose()
        toast(i18n.t('common.base.tip.updateSuccess'), 'success');
        this.getTableData()
      })
    },

    // 查看任务详情 跳转到任务详情页面
    openTaskViewTab(row) {
      let fromId = window.frameElement.getAttribute('id');
      if (row?.taskType && row?.taskType === 'WORK_TASK') {
        // 工单类型的任务
        if (row?.taskBizId) {
          openAccurateTab({
            type: PageRoutesTypeEnum.PageTaskView,
            key: row.taskBizId,
            titleKey: row.taskFormName,
            params: 'noHistory=1'
          })
        } else {
          this.$message.error(this.$t('common.projectManage.editTip2'))
        }
      }else if (row?.taskType === 'PAAS_TASK') {
        openTaskManageViewTab(row)
      } else {
        openAccurateTab({
          type: PageRoutesTypeEnum.PageTaskManageView,
          params: `id=${row.id}&projectId=${row.projectId}`,
          reload: true,
          fromId,
        });
      }
    },
    // 获取任务详情和任务表单详情
    getTaskDetail(item, type) {
       ProjectManage.taskDetailPro({id: item.id, projectId: this.projectId}).then( async(res) => {
        if (!res.success) return this.$message.error(res.message)
        this.taskForm = {
          id: item.id || '',
          preTaskId: (res.data.preTaskInfoList || []).map((item) => (item.id)),
          ...res.data,
        }
        if ( item.taskType !== 'COMMON_TASK' || type === 'draft') {
          // 草稿状态的话，直接打开弹窗，不用请求通用任务详情接口
          this.$refs.CreateProjectTaskModal.openDialog(this.taskForm, true, type)
        } else {
          // 新建任务和编辑任务的时候调用
          // 通用任务类型
          await this.getCommonTaskDetail(res?.data?.taskBizId, type)
        }
      })
    },


    // 获取通用任务表单详情
    getCommonTaskDetail(taskBizId, type) {
      ProjectManage.comTaskDetailPro({id: taskBizId}).then((res) => {
        if (!res.success) return this.$message.error(res.message)
        this.commonTaskForm = res?.data || {}

        this.commonTaskForm.commonId = taskBizId  // 详细的任务表单id
        delete this.commonTaskForm?.id // 去掉详细的任务表单id
        this.taskDetailForm = {...this.taskForm, ...this.commonTaskForm}

        // 打开编辑弹窗 type区分编辑还是草稿提交
        this.$refs.CreateProjectTaskModal.openDialog(this.taskDetailForm, true, type)
      })
    },

    // 删除当前任务
    taskDelete(row) {
      let params = {
        projectId: this.projectId,
        id: row.id,
      }
      this.$confirm(this.$t('projectManage.taskManageView.deleteMsg'), this.$t('common.base.toast'), {
        confirmButtonText: this.$t('common.base.makeSure'),
        cancelButtonText: this.$t('common.base.cancel'),
        type: 'warning',
      })
      .then(() => {
        ProjectManage.taskDeletePro(params).then((res) => {
          if (!res.success) return this.$message.error(res.message)
          this.$emit('updateProcess')
          toast(i18n.t('common.base.tip.deleteSuccess'), 'success');
          this.getTableData()
        })

      }).catch(() => { });
    },
    // 提交创建的任务字段
    submitTask(form, isEdit, actionType) {
      let params = {
        ...form,
      }
      if (actionType === 'draft') {
      // 暂存状态
        ProjectManage.updateTaskAndAddCommonTask(params).then((res) => {
          this.commonAction(res)
        })
      } else {
        // 编辑任务
        if (isEdit) {
          ProjectManage.updateTaskAndCommonTask(params).then((res) => {
            this.commonAction(res)
          })
        } else {
          // 新增任务
            // 新增时，弹窗提示，“任务数量变更会导致进度权重的重置，确认继续？”确认后重置权重
            ProjectManage.addTaskAndCommonTask(params).then((res) => {
              this.commonAction(res, actionType)
            })
        }
      }
    },

    commonAction(res, actionType) {
      if (!res.success) return this.$message.error(res.message)
      toast(i18n.t('common.base.tip.operationSuccess'), 'success');
      if (actionType === 'add') {
        // 新增任务的时候 更新项目进度
        this.$emit('updateProcess')
      }
      this.$refs.CreateProjectTaskModal.closeDialog()
      this.getTableData()
    },

    fixedColumns() {
      return  [
        {
          displayName: this.$t('projectManage.setting.taskSetting.taskNum'),
          field: 'taskNumber',
          minWidth: '180px'
        },
        {
          displayName: this.$t('projectManage.setting.taskSetting.taskName'),
          field: 'projectTaskName',
          minWidth: '180px'
        },
        {
          displayName: this.$t('projectManage.taskManageList.text1'),
          field: 'taskProgress',
          minWidth: '180px'
        },
        {
          displayName: this.$t('projectManage.setting.taskSetting.taskType'),
          field: 'taskType',
          minWidth: '180px'
        },
        {
          displayName: this.$t('projectManage.taskManageList.text2'),
          field: 'taskBizNumber',
          minWidth: '180px'
        },
        {
          displayName: this.$t('projectManage.taskManageList.taskStatus'),
          field: 'taskStatus',
        },
        {
          displayName: this.$t('common.task.flow.planStartTime'),
          field: 'planStartTime',
          minWidth: '180px'
        },
        {
          displayName: this.$t('common.task.flow.planFinishTime'),
          field: 'planEndTime',
          minWidth: '180px'
        },
        {
          displayName: this.$t('projectManage.taskManageList.text4'),
          field: 'preTaskInfoList',
        },
        {
          displayName: this.$t('common.label.principalName'), 
          field: 'manager',
        },
        {
          displayName: this.$t('projectManage.setting.taskSetting.projectContent'),
          field: 'projectTaskDesc',
        }
      ]
    },
  }
  
}
</script>
<style lang="scss" scoped>
.task-list-wrap {
  .header-top {
    display: flex;
    justify-content: space-between
  }
  .add-task-btn {
    flex: 1;
    text-align: left;
    .el-button--mini {
      border-radius: 4px;
    }
  }
  .pop-item {
    margin-right: 220px;
    margin-top: -28px;

  }
  .text-danger {
    color: #f56c6c!important;
  }
  ::v-deep .el-progress {
    width: 100%;

    &__text {
      font-size: $font-size-small !important;
    }
  }
  .el-table {
    .status-tag {
      padding: 0 8px;
      background-color: $color-ding-blue;
      line-height: 22px;
      border-radius: 22px;
      color: #fff;
      font-size: 12px;
    }

    .el-progress {
      width: 100%;
    }
  }
}
</style>